package com.dabai.sas.activitys;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.dabai.sas.R;
import com.dabai.sas.utils.DabaiUtils;
import com.dabai.sas.utils.FileUtil;
import com.dabai.sas.utils.KFileUtil;
import com.dabai.sas.utils.UriUtils;
import com.google.android.material.chip.Chip;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.util.Objects;

import io.noties.markwon.Markwon;

public class MdViewerActivity extends AppCompatActivity {

    TextView tv1, tv2;
    Chip chip1;
    Context context;
    Markwon markwon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_md_viewer);

        context = getApplicationContext();

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DabaiUtils.showToast(context, "请点击申请'储存权限'!");
            startActivity(new Intent(this, PermissionsActivity.class));
            finish();
            return;
        }


        tv1 = findViewById(R.id.textView1);
        tv2 = findViewById(R.id.textView2);
        chip1 = findViewById(R.id.chip1);

        // obtain an instance of Markwon
        markwon = Markwon.create(context);

        init();

    }


    /**
     * 程序启动
     */
    private void init() {

        try {

            //拿到uri
            Uri uri = getIntent().getData();
            String fileText = "";

            if (uri.toString().startsWith("file:///")) {
                File file = new File(FileUtil.getFileAbsolutePath(this, uri));

                tv1.setText(file.getName());
                fileText = new KFileUtil().readText(file);

            } else {
                UriUtils file = new UriUtils(context, uri);
                tv1.setText(file.getFileName());
                fileText = file.readFileText();

            }

            chip1.setText("字数:" + fileText.length());
            markwon.setMarkdown(tv2, fileText + '\u3000');

        } catch (Exception e) {
            Toast.makeText(context, "程序异常!", Toast.LENGTH_SHORT).show();
            //finish();
            return;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}